package com.atguigu.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.SubjectData;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class SubjectDataListener extends AnalysisEventListener<SubjectData> {

    @Autowired
    SubjectMapper subjectMapper;

    //public SubjectDataListener(SubjectMapper subjectMapper){
    //    this.subjectMapper=subjectMapper;
    //}

    //每解析到一行数据的回调方法，处理读取到的一行数据
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        String levelOneSubjectTitle = subjectData.getLevelOneSubjectTitle();
        String levelTwoSubjectTitle = subjectData.getLevelTwoSubjectTitle();
        //持久化数据
        //将导入的一行数据转为数据库中的一.
        //1.获取一级分类信息保存到数据库
        //判断一级目录是否存在，如果存在不保存，如果不存在保存
        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Subject::getTitle, levelOneSubjectTitle);
        queryWrapper.eq(Subject::getParentId, 0);
        Subject pSubject = subjectMapper.selectOne(queryWrapper);//mapper对象为空指针，装配失败
        if (pSubject == null) {
            pSubject = new Subject();
            pSubject.setTitle(levelOneSubjectTitle);
            pSubject.setParentId("0");
            pSubject.setSort(0);
            subjectMapper.insert(pSubject);
        }
        //二级分类
        // 获取二级分类的信息 并设置一级分类的id为自己的父id存到数据库
        //判断二级分类是否存在
        queryWrapper.clear();
        queryWrapper.eq(Subject::getParentId, pSubject.getId());//如果二级目录的id等于一级目录parentId则说明属于子分类
        queryWrapper.eq(Subject::getTitle, levelTwoSubjectTitle);
        if (subjectMapper.selectCount(queryWrapper) == 0) {//如果能查到，则不保存  等于0说明不存在则执行新增操作
            //保存二级目录
            Subject cSubject = new Subject();
            cSubject.setTitle(levelTwoSubjectTitle);
            cSubject.setSort(0);
            cSubject.setParentId(pSubject.getId());//将父级目录id设置给子目录的id
            subjectMapper.insert(cSubject);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
